<?php

/**
* -------------------------------------------------------------------------------------------------------------------
* @abstract   Handles the CRUD operations for User and other methods
* @package    Kiropedic
* @subpackage Controllers
* @author     Darwing Hernández - darwing.her69@gmail.com
* -------------------------------------------------------------------------------------------------------------------
*/

class UserController extends BaseController
{

  /**
  * ---------------------------------------------------------------------------------------------------------------
  * ATTRIBUTES AND CONSTANTS
  * ---------------------------------------------------------------------------------------------------------------
  */

  public $restful = true;

  /**
  * ---------------------------------------------------------------------------------------------------------------
  * VIEWS
  * ---------------------------------------------------------------------------------------------------------------
  */

  public function newUser()
  {
    return View::make('kir.register')->with('title', 'Registro de Cliente');
  }

  public function login()
  {
    return View::make('kir.login')->with('title', 'Inicio de Sesión');
  }

  /**
  * ---------------------------------------------------------------------------------------------------------------
  * CRUD OPERATIONS
  * ---------------------------------------------------------------------------------------------------------------
  */

  /**
  * CREATE Operation
  * @abstract creates a new user record
  * @param    int - mode to create the user (1: public, 2: admin)
  * @return   View
  * @access   public
  */
  public function create($mode)
  {
    if($mode != 1 && $mode != 2) return Response::view('errors.404', array(), 404);
    elseif($mode == 1)
    {
      // public

      $input = Input::get();
      $input['ncedula'] = Input::get('r1').Input::get('cedula');

      // Validates the input
      if (!$this->validate($input, CREATE_USER_KIR))
        return Redirect::to('newuser')->withErrors($this->validation);

      // Creates the user
      $user = User::create(array(
        'usr_name'      =>  $input['nombre'],
        'usr_rifci'     =>  $input['ncedula'],
        'usr_cellphone' =>  $input['telefono'],
        'usr_active'    =>  1,
        'usr_status'    =>  0
      ));

      // Caching some useful data of the user
      Cache::put ('usr_name',   $user->usr_name,  10);
      Cache::put ('usr_rifci',  $user->usr_rifci, 10);
      Cache::put ('usr_code',   $user->usr_code,  10);

      return Redirect::to('welcome');
    }
    elseif($mode == 2)
    {
      // admin
      $input  = Input::all();
      $index  = array('cedula');
      $values = array('unique:user_usr,usr_rifci');

      // Validates the input
      if (!$this->validate($input, CREATE_USER, $index, $values))
        return  Redirect::to('admin/create/user')
                        ->with('notification', 'register_add_warning')
                        ->with('opt', 'El cliente ')
                        ->withErrors($this->validation)
                        ->withInput();

      // Creates the user
      $user = User::create(array(
        'usr_name'      =>  $input['nombre'],
        'usr_rifci'     =>  $input['ncedula'],
        'usr_cellphone' =>  $input['telefono'],
        'usr_active'    =>  1,
        'usr_status'    =>  0
      ));

      // Redirects to the same page form if user specified add more registers
      if(Input::get('again') == "on")
        return Redirect::to('admin/create/user')->with('notification', 'register_add_success')->with('opt', 'El cliente ');
      else
        return Redirect::to('admin/list/listuser')->with('notification', 'register_add_success')->with('opt', 'El cliente ');
    }
  }

  /**
  * READ Operation
  * @abstract  Reads a record by id and shows the related data
  * @param     int - record ID
  * @return    View
  * @access    public
  */
  public function view($id)
  {
    $user = User::select('usr_code', 'usr_name', 'usr_rifci', 'usr_cellphone', 'usr_active')->find($id);

    if(!$user) return Redirect::to('admin/list/listuser')->with('notification', 'not_allowed');

    return View::make('admin.user.editUser')->with('user', $user)->with('title', 'Editar Cliente')->with('active', 2);
  }

  /**
  * UPDATE Operation
  * @abstract  updates a record by id
  * @param     int - record ID
  * @return    View
  * @access    public
  */
  public function update($id)
  {
    $index  = array('cedula');
    $values = array('unique:user_usr,usr_rifci,'.$id.',usr_code');

    // Validates the input
    if(!$this->validate(Input::all(), UPDATE_USER, $index, $values))
      return Redirect::to('admin/viewUser/'.$id)->withErrors($this->validation)->withInput()->with('notification', 'register_edit_warning');

    $user                 = User::find($id);
    $user->usr_name       = Input::get('nombre');
    $user->usr_rifci      = Input::get('cedula');
    $user->usr_cellphone  = Input::get('telefono');
    $user->usr_active     = Input::get('active') == "on"? 1: 0;
    $user->save();

    return Redirect::to('admin/viewUser/'.$id)->with('notification', 'register_edit_success');
  }

  /**
  * DELETE Operation
  * @abstract deletes records by specified IDs
  * @access   public
  */
  public static function delete($keys)
  {
    User::destroy($keys);
    return Redirect::to('admin/list/listuser')->with('notification', 'register_delete_success');
  }

  /**
  * ---------------------------------------------------------------------------------------------------------------
  * OTHER METHODS/ACTIONS AND STUFF
  * ---------------------------------------------------------------------------------------------------------------
  */

  /**
  * @abstract Log in a user in the public system
  * @access   public
  */
  public function olduser()
  {
    $user = DB::table('user_usr')->select('usr_code')
                ->where('usr_rifci', Input::get('r1').Input::get('cedula'))
                ->where('usr_status', '<', 2)
                ->where('usr_active', '=', 1)->get();

    if (!$user) return Redirect::to('olduser')->with('login_errors', true);

    $user = User::find($user[0]['usr_code']);
    $user->usr_status = 1;
    $user->save();

    Cache::put('usr_name',  $user['usr_name'],  10);
    Cache::put('usr_rifci', $user['usr_rifci'], 10);
    Cache::put('usr_code',  $user['usr_code'],  10);

    return Redirect::to('welcome')->with('title', 'Selección de Servicios');
  }

  /**
  * @abstract finishes the request and shows the final info for the user
  * @access   public
  */
  public function endRequest()
  {
    $idope = Input::get('d077f244def8a70');

    $result = DB::table('operator_ope')
                    ->where('ope_code', $idope)
                    ->pluck('ope_name');

    return View::make('kir.ending')->with('name', $result)->with('title', 'Hemos terminado');
  }

}